package com.example.demo.controller;


import com.example.demo.common.AjaxResult;
import com.example.demo.common.PasswordUtils;
import com.example.demo.common.UserSessionUtils;
import com.example.demo.entity.Personalinfo;
import com.example.demo.entity.SafeAnswerinfo;
import com.example.demo.entity.SafeQuestioninfo;
import com.example.demo.entity.Userinfo;
import com.example.demo.service.PersonalService;
import com.example.demo.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/personal")
public class PersonalController {

    @Autowired
    private PersonalService personalService;
    @Autowired
    private UserService userService;

    //展示个人信息
    @RequestMapping("/showpersonalinfo")
    public AjaxResult showPersonalInfo(HttpServletRequest request){
        //判断当前登录用户
        Userinfo userinfo = UserSessionUtils.getSessionUser(request);
        if (userinfo==null || userinfo.getId()<=0){
            return AjaxResult.fail(-1,"请先登录",null);
        }
        int uid = userinfo.getId();
        Personalinfo personalinfo = personalService.showPersonalInfo(uid);

        //查询当前用户是否是管理员
        int admin = userinfo.getAdmin();

        if (admin == 0){
            return AjaxResult.success(200,userinfo.getPhoto(),personalinfo);
        }
        if(admin==1){
            return AjaxResult.success(201,userinfo.getPhoto(),personalinfo);
        }
        return AjaxResult.fail(-1);
    }

    //更新个人信息
    @RequestMapping("/update")
    public AjaxResult update(HttpServletRequest request,Personalinfo personalinfo){
        //判断用户是否登录
        Userinfo userinfo = UserSessionUtils.getSessionUser(request);
        if (userinfo==null || userinfo.getId()<=0){
            return AjaxResult.fail(-1,"请先登录",null);
        }
        //更新数据库
        personalinfo.setUid(userinfo.getId());
        return AjaxResult.success(personalService.update(personalinfo));

    }

    //显示密保问题与答案
    @RequestMapping("/getsafequestion")
    public AjaxResult getSafeQuestion(HttpServletRequest request){
        //验证当前登录用户
        Userinfo userinfo = UserSessionUtils.getSessionUser(request);
        if (userinfo==null || userinfo.getId()<=0){
            return AjaxResult.fail(-1,"请先登录",null);
        }
        int uid = userinfo.getId();
        //在数据库中查找问题和答案存入hashmap里面
        LinkedHashMap<String,String> map = new LinkedHashMap<>();
        List<SafeQuestioninfo> questions = personalService.getSafeQuestion(uid,0);  //查询密保问题，uid为0和当前登录用户
        List<SafeAnswerinfo> answer = personalService.getAnswer(uid);  //查询当前登录用户的答案

        //将问题列表放入hashmap里面
//        map.put("question",questions);
        //遍历questions列表，将每个问题的为key，对应答案为value放入map中
        for(int i=0;i<questions.size();i++){
            int qid = questions.get(i).getId();
            int flag = 1;
            //在answer里面遍历答案，当qid和某项答案的qid一样时，停止循环，将这个答案put到map里面
            for(int j = 0;j<answer.size();j++){
                if (answer.get(j).getQid() == qid){
                    map.put(questions.get(i).getQuestion(),answer.get(j).getAnswer());
                    flag =0;
                    break;
                }
            }
            if (flag==1){
                map.put(questions.get(i).getQuestion(),"");
            }
        }

        return AjaxResult.success(map);



    }

    //存储或更新密保信息
    @RequestMapping("/editsafeanswer")
    public AjaxResult editSafeQuestion(HttpServletRequest request,String answer,Integer qid) {
        //验证当前登录用户
        Userinfo userinfo = UserSessionUtils.getSessionUser(request);
        if (userinfo==null || userinfo.getId()<=0){
            return AjaxResult.fail(-1,"请先登录",null);
        }
        int uid = userinfo.getId();
        //将answer中的空格去除
        answer = answer.replaceAll(" ","");
        System.out.println("问题："+answer+"所属qid："+qid);//正确拿到答案和所属问题id

        //更新词条数据。根据uid和qid
        SafeAnswerinfo answerinfo = new SafeAnswerinfo();
        answerinfo.setUid(uid);
        answerinfo.setQid(qid);
        answerinfo.setAnswer(answer);
        //先在数据库中找到此uid qid的数据，如果有数据就更新，如果没有数据就插入
        SafeAnswerinfo answerinfo1 = personalService.getAnswerByUidQid(answerinfo);
        if (answerinfo1==null){
            //插入数据
            personalService.addAnswerByUidQid(answerinfo);
            return AjaxResult.success(200,"保存成功",1);
        }
        //更新数据
        personalService.updateAnswerByUidQid(answerinfo);

        return AjaxResult.success(200,"保存成功",1);




    }

    //修改密码
    @RequestMapping("/updatepwd")
    public AjaxResult updatePwd(HttpServletRequest request,String oldpwd,String newpwd){
        //验证当前登录用户
        Userinfo userinfo = UserSessionUtils.getSessionUser(request);
        if (userinfo==null || userinfo.getId()<=0){
            return AjaxResult.fail(-1,"请先登录",null);
        }
        if (oldpwd.equals(newpwd)){
            return AjaxResult.fail(-1,"不能和原始密码一样",null);
        }
        Userinfo userinfo1 = userService.getUserByName(userinfo.getUsername());
        System.out.println("old:"+oldpwd);
        System.out.println("new:"+newpwd);
        System.out.println(userinfo1);
        //将之前的密码，和oldpwd对比
        if (PasswordUtils.check(oldpwd,userinfo1.getPassword())) {
            //对比成功则更新密码
            //将密码加盐
            newpwd = PasswordUtils.encrypt(newpwd);
            return AjaxResult.success(personalService.updatePassword(newpwd,userinfo.getId()));
        }else {
            return AjaxResult.fail(-1,"原始密码不正确",null);
        }




    }

    //忘记密码时修改密码
    private String str = "";
    @RequestMapping("/forgetpwd")
    public AjaxResult forgetpwd(String answer,String username,String pwd,Integer index){
        //判断
        if(answer==""){
            return AjaxResult.fail(-1,"请输入完整的密保问题答案",null);
        }
        if(username==""){
            return AjaxResult.fail(-1,"请输入用户名",null);
        }
        if(pwd == ""){
            return AjaxResult.fail(-1,"请输入密码",null);
        }

        //根据用户名从userinfo表里面找此用户的id
        Userinfo userinfo = userService.getUserByName(username);
        if(userinfo==null || userinfo.getId()<=0){
            return AjaxResult.fail(-1,"用户名错误",null);
        }
        int uid = userinfo.getId();
        //然后根据uid，从answerinfo表里面找密保答案
        List<SafeAnswerinfo> list1 = personalService.getAnswer(uid);
        if (list1==null || list1.get(index).getAnswer().equals("")){
            System.out.println(list1);
            return AjaxResult.fail(-1,"当前没有设置密保信息,请联系管理员",null);
        }
        //然后看密保答案和当前输入的密保答案是否一样
        SafeAnswerinfo answerinfo = list1.get(index);
        if (!(answerinfo.getAnswer().equals(answer))){
            return AjaxResult.fail(-1,"密保问题答案错误",null);
        }else {
            str+=1;
        }

        if (str.equals("111")){
            //更新密码
            str="";
            return AjaxResult.success(personalService.updatePassword(PasswordUtils.encrypt(pwd),uid));
        }
        if (index==list1.size()-1){
            str="";
        }

        return AjaxResult.fail(-2,"稍等",null);

    }

    //显示密保问题
    @RequestMapping("/getsafequestion1")
    public AjaxResult getSafeQuestion1(){

       //查询密保问题，依次存放到list数组中
        List<SafeQuestioninfo> list = personalService.getSafeQuestion(0,0);
        //将list返回
        return AjaxResult.success(list);

    }




}
